#include <iostream>
#include <queue>
#include <thread>
#include <mutex>
#include <condition_variable>
#include <functional>

class AsyncProxy {
private:
    std::queue<std::function<void()>> tasks;
    std::mutex mtx;
    std::condition_variable cv;
    bool stopped = false;

    void worker() {
        while (true) {
            std::function<void()> task;
            {
                std::unique_lock<std::mutex> lock(mtx);
                cv.wait(lock, [this] { return !tasks.empty() || stopped; });
                if (stopped && tasks.empty()) break;
                task = std::move(tasks.front());
                tasks.pop();
            }
            task(); 								// 执行任务
        }
    }

public:
    AsyncProxy() {
        std::thread(&AsyncProxy::worker, this).detach();
    }

    ~AsyncProxy() {
        {
            std::lock_guard<std::mutex> lock(mtx);
            stopped = true;
        }
        cv.notify_all();
    }

    void addTask(const std::function<void()>& task) {
        {
            std::lock_guard<std::mutex> lock(mtx);
            tasks.push(task);
        }
        cv.notify_one();
    }
};

void handleRequest() {
    std::cout << "Handling request asynchronously." << std::endl;
}

int main() {
    AsyncProxy proxy;
    proxy.addTask(handleRequest);
    proxy.addTask(handleRequest);
    std::this_thread::sleep_for(std::chrono::seconds(1)); // 模拟等待更多任务
    return 0;
}